package com.hiwan.unions.activity.loginRegister;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hiwan.unions.R;
import com.hiwan.unions.activity.base.RootActivity;
import com.hiwan.unions.activity.main.MainActivity;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.exception.ApiException;
import com.hiwan.unions.application.request.CallServer;
import com.hiwan.unions.application.request.ConstsNet;
import com.hiwan.unions.application.request.HttpListener;
import com.hiwan.unions.util.AESKit;
import com.hiwan.unions.util.Base64Util;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.EditUtils;
import com.hiwan.unions.util.ExampleUtil;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.SystemUtil;
import com.hiwan.unions.util.ToastUtils;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONObject;


/**
 * 忘记密码//注册
 */
public class RegisterPasswordUpdateActivity extends RootActivity implements HttpListener<JSONObject> {
    private EditText edit_password, yzm_et, edit_phone;
    private Button yzm_button;
    private boolean type = true;
    private TextView textPassword, zhuc;
    String mMobile;
    String password, yzmString;
    Request<JSONObject> request;
    String p = "";
    private ImageView imageView;
    boolean eyeOpen = false;

    public static void startPreview(Activity context, boolean type) {
        Intent intent = new Intent(context, RegisterPasswordUpdateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("type", type);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_password_update_register;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onViewCreated() {
        super.onViewCreated();
        edit_phone = findView(R.id.edit_phone);
        EditUtils.phoneNumAddSpace(edit_phone);
        edit_password = findView(R.id.edit_password);
        imageView = findView(R.id.image);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eyeOpen = EditUtils.YjImage(imageView, edit_password, eyeOpen);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bundle = getIntent().getExtras();
        type = bundle.getBoolean("type");
        edit_phone = findView(R.id.edit_phone);
        zhuc = findView(R.id.zhuc);
        yzm_et = findView(R.id.yzm_et);
        textPassword = findView(R.id.textPassword);
        yzm_button = findView(R.id.yzm_button);
        EditUtils.phoneNumAddSpace(edit_phone);
        edit_password = findView(R.id.edit_password);
        if (type) {
            setTitleTxt("注册");
            zhuc.setText("已有账号");
            textPassword.setText("设置密码");
            confirmButton.setText("注册");
        } else {
            setTitleTxt("忘记密码");
            confirmButton.setText("确定");
            zhuc.setText("登录");
            textPassword.setText("重设密码");
        }
    }

    public void ButtonOnClick(View view) {
        switch (view.getId()) {
            case R.id.yzm_button:
                setYzm();
                break;
            case R.id.zhuc:
                finish();
                break;
        }
    }

    private void setYzm() {
        try {
            mMobile = CheckUtils.checkMobile(edit_phone);
        } catch (ApiException e) {
            ToastUtils.showToast(this, e.getMessage());
            return;
        }
        if (type) {
            request = NoHttp.createJsonObjectRequest(ConstsNet.captcha, RequestMethod.POST);
        } else {
            request = NoHttp.createJsonObjectRequest(ConstsNet.captcha_customer, RequestMethod.POST);
        }
        request.add("mobile", mMobile);
        CallServer.getRequestInstance().add(this, 0, request, this, true);
    }

    private CountDownTimer timerButton = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            yzm_button.setEnabled(false);
            yzm_button.setText((millisUntilFinished / 1000) + "s");
        }

        @Override
        public void onFinish() {
            yzm_button.setEnabled(true);
            yzm_button.setText("重新获取");
        }
    };

    @Override
    protected void IntentConfirm() {
        super.IntentConfirm();
        try {
            mMobile = CheckUtils.checkMobile(edit_phone);
            password = CheckUtils.checkRegisterPaaword(edit_password);
            yzmString = CheckUtils.checkYzm(yzm_et);
        } catch (ApiException e) {
            ToastUtils.showToast(this, e.getMessage());
            return;
        }
        if (type) {
            request = NoHttp.createJsonObjectRequest(ConstsNet.registry, RequestMethod.POST);
            request.add("city", userInfoC.getString(ConstantsValues.CITYNAMEOne, ""));
            request.add("longitude", userInfoC.getString(ConstantsValues.longitude, ""));
            request.add("latitude", userInfoC.getString(ConstantsValues.latitude, ""));
        } else {
            request = NoHttp.createJsonObjectRequest(ConstsNet.resetPassword, RequestMethod.POST);
        }
        request.add("mobile", mMobile);
        request.add("captcha", yzmString);
        request.add("password", password);
        if (type) {
            CallServer.getRequestInstance().addToken(this, 1, request, this, true, userInfo);
        } else {
            CallServer.getRequestInstance().addToken(this, 2, request, this, true, userInfo);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timerButton != null) {
            timerButton.cancel();
            timerButton = null;
        }
    }

    @Override
    public void onSucceed(int what, Response<JSONObject> response) {
        JSONObject jsonObject = response.get();
        jsonObject = JsonUtil.getJSONObject(jsonObject, "data");
        ToastUtils.showToast(this, JsonUtil.getString(jsonObject, "msg"));
        SharedPreferences.Editor editor = userInfo.edit();
        switch (what) {
            case 0:
                editor.putString(ConstantsValues.AUTHTOKEN, AESKit.encryptAndBase64(JsonUtil.getString(jsonObject, "authtoken"), ConstantsValues.ASEKIPASSWORD));
                editor.commit();
                timerButton.start();
                break;
            case 1:
                ToastUtils.showToast();
                try {
                    JSONObject m = new JSONObject();
                    m.put("password", Base64Util.decodeStrNoTry(password));
                    m.put("loginname", mMobile);
                    m.put("imei", SystemUtil.getImei(this));
                    m.put("t", String.valueOf(System.currentTimeMillis()));
                    m.put("client", "app");
                    m.put("device", "10");
                    m.put("phoneType", ExampleUtil.getModel());
                    m.put("phoneVersion", ExampleUtil.getRelease());
                    m.put("appVersion", ExampleUtil.GetVersion(this));
                    m.put("city", userInfoC.getString(ConstantsValues.CITYNAME, "成都市"));
                    p = m.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                p = Base64Util.encode(Base64Util.encrypt(p.getBytes(), ConstantsValues.DESPASSWORD.getBytes()));
                Request<JSONObject> request = NoHttp.createJsonObjectRequest(ConstsNet.login, RequestMethod.POST);
                request.add("p", p);
                CallServer.getRequestInstance().add(this, 3, request, this, true);
                break;
            case 2:
                finish();
                break;
            case 3:
                editor.putBoolean(ConstantsValues.IS_HASLOGIN, true);
                editor.putString(ConstantsValues.uuid, AESKit.encryptAndBase64(JsonUtil.getString(jsonObject, "uuid"), ConstantsValues.ASEKIPASSWORD));
                editor.putString(ConstantsValues.AUTHTOKEN, AESKit.encryptAndBase64(JsonUtil.getString(jsonObject, "authtoken"), ConstantsValues.ASEKIPASSWORD));
                editor.putString(ConstantsValues.phone, mMobile);
                editor.commit();
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;

        }

    }

    @Override
    public void onFailed(int what, int errCode, String networkMillis, boolean type) {
        ToastUtils.showToast(this, networkMillis);
    }
}

